package org.keshe.controllers;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import org.keshe.CurrentUser;
import org.keshe.gui.Main;
import org.keshe.gui.PublicStages;
import org.keshe.user.AdminUser;
import org.keshe.user.NormalUser;

import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class LogOn implements Initializable {

    @FXML
    private TextField usr;

    @FXML
    private PasswordField pwd;

    @FXML
    private Button Normalsubmit;

    @FXML
    private Button Adminsubmit;

    private Alert alert1, alert2, alert3;

    @FXML
    void NormallogOn(ActionEvent event)  {
        if(usr.getText().isEmpty() || pwd.getText().isEmpty()) {
            alert1.show();
            return;
        }
        NormalUser normalUser;
        try {
            normalUser = NormalUser.logOn(usr.getText(), pwd.getText());
            if(normalUser != null){
                // 登录成功
                CurrentUser.USER = normalUser;
                PublicStages.loadMasterStages();
                PublicStages.MASTERMENU.show();
                Main.logOnStage.close();
            }
            else {
                alert2.show();
            }
        } catch (SQLException | NullPointerException | IOException e) {
            alert3.show();
            throw new RuntimeException(e);
        }
    }

    @FXML
    void AdminlogOn(ActionEvent event) {
        if(usr.getText().isEmpty() || pwd.getText().isEmpty()) {
            alert1.show();
            return;
        }
        AdminUser adminUser;
        try {
            adminUser = AdminUser.logOn(usr.getText(), pwd.getText());
            if(adminUser != null){
                // 登录成功
                CurrentUser.USER = adminUser;

                PublicStages.loadAdminStages();
                PublicStages.ADMINMENU.show();
                Main.logOnStage.close();
            }
            else {
                alert2.show();
            }
        } catch (SQLException | NullPointerException | IOException e) {
            alert3.show();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        alert1 = new Alert(Alert.AlertType.WARNING, "用户名或密码不能为空", ButtonType.OK);
        alert2 = new Alert(Alert.AlertType.WARNING, "用户名或密码错误", ButtonType.OK);
        alert3 = new Alert(Alert.AlertType.ERROR, "未知错误", ButtonType.OK);
    }
}